package com.jse.util;

import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import org.nutz.ioc.impl.PropertiesProxy;

public class UrlUtil {
	
	private final static Set<String> PublicSuffixSet = new HashSet<String>(  
            Arrays.asList(new String(  
                    "com|org|net|gov|edu|co|tv|mobi|info|asia|xxx|onion|cn|com.cn|edu.cn|gov.cn|net.cn|org.cn|jp|kr|tw|com.hk|hk|com.hk|org.hk|se|com.se|org.se")  
                    .split("\\|")));  

	private static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");  

	/** 
     * 获取链接的后缀名 
     * @param url 获取的链接
     * @return 
     */  
    public static String getSuffix(String url) {
    	if(url==null||url.lastIndexOf(".")==-1) {
    		return "";
    	}else {
    		return url.substring(url.lastIndexOf(".") + 1);
    	}
    }
    /** 
     * 获取去除后缀的链接 
     * @param url 获取的链接
     * @return 
     */  
    public static String getUrl(String url) {
    	if(url.lastIndexOf(".")==-1) {
    		return url;
    	}else {
    		return url.substring(0,url.lastIndexOf("."));
    	}
    }
    /** 
     * 获取去除后缀的链接 
     * @param url 获取的链接
     * @return 
     */  
    public static JseMap getAction(String url,JseMap param,PropertiesProxy conf) {
    	List<String> paths=getPaths(url);
    	String suffix=UrlUtil.getSuffix(url);
    	StringBuffer jjs=new StringBuffer();
    	String func="index";
    	String page="";
    		if(paths.size()==0) {
    			func="index";
    			page="index.html";
    		}else if(paths.size()==1) {
    			func=paths.get(0).equals("")?"index":paths.get(0);
    			page=func.concat(".html");
    		}else if(paths.size()==2) {
    			String a1=paths.get(0);
    			jjs.append(a1);
    			String key=paths.get(1);
    			if(key.length()>29) {
    				param.put("id", key);
    				func=a1;
    			}else if(Strings.isNumber(key)) {
    				param.put("id", key);
    				func=a1;
    			}else if(Strings.isChinese(key)) {
    				param.put("name", key);
    				func=a1;
    			}else {
    				func=key;
    			}
    			page=jjs.toString().concat("/").concat(func).concat(".html");
    		}else if(paths.size()==3) {
    			//扩展功能 json raw txt xml
    			if(conf!=null&&List.of("html","json","raw","txt","xml").contains(paths.get(0))) {
    				jjs.append(paths.get(1));
        			func=paths.get(2);
        			page=paths.get(0);
    			}else {
    				jjs.append(paths.get(0));
        			func=paths.get(1);
        			String key=paths.get(2);
        			if(key.length()>29) {
        				param.put("id", key);
        				page=jjs.toString().concat("/").concat(func).concat(".html");
        			}else if(Strings.isNumber(key)) {
        				param.put("id", key);
        				page=jjs.toString().concat("/").concat(func).concat(".html");
        			}else if(Strings.isChinese(key)) {
        				param.put("name", key);
        				page=jjs.toString().concat("/").concat(func).concat(".html");
        			}else {
        				page=jjs.toString().concat("/").concat(func).concat("/").concat(paths.get(2)).concat(".html");
        				func=paths.get(2);
        				jjs.append("/").append(paths.get(1));
        			}
    			}
    		}else if(paths.size()%2==0){
    			jjs.append(paths.get(0));
    			func=paths.get(1);
    			for (int i = 2; i < paths.size(); i++) {
    				param.put(paths.get(i), paths.get(i+1));
    				i++;
				}
    			page=jjs.toString().concat("/").concat(func).concat(".html");
    		}else {
    			jjs.append(paths.get(0));
    			func=paths.get(1);
    			param.put("id", paths.get(2));
    			for (int i = 3; i < paths.size(); i++) {
    				param.put(paths.get(i), paths.get(i+1));
    				i++;
				}
    			page=jjs.toString().concat("/").concat(func).concat(".html");
    		}
    	JseMap actions=new JseMap();
    	actions.put("jjs", jjs.toString());
    	actions.put("func", func);
    	actions.put("page", page);
    	actions.put("suffix", suffix);
    	actions.put("p", param);
		return actions;
    }
    
    /**
     * 获取的servlet请求 第一个为/
     * @param url
     * @return
     */
    public static List<String> getPaths(String url) {
    	if(url==null||url.equals("")) {
    		return Arrays.asList("");
    	}
    	String action=getUrl(url).substring(1);
    	if(action.endsWith("/")) {
    		action=action.concat("index");
    	}
    	return Arrays.asList(action.split("/"));
    }
    
    /** 
     * 获取url的顶级域名 
     * @param url 
     * @return 
     */  
    public static String getDomain(String uri) {  
    	try {
    		URL url=new URL(uri);
    		String host = url.getHost();  
            if (host.endsWith("."))  
                host = host.substring(0, host.length() - 1);  
            if (IP_PATTERN.matcher(host).matches())  
                return host;  
      
            int index = 0;  
            String candidate = host;  
            for (; index >= 0;) {  
                index = candidate.indexOf('.');  
                String subCandidate = candidate.substring(index + 1);  
                if (PublicSuffixSet.contains(subCandidate)) {  
                    return candidate;  
                }  
                candidate = subCandidate;  
            }  
            return candidate;  
		} catch (Exception e) {
			System.err.println(String.format("get domain %s err:%s",uri, e.getMessage()));
			return uri.replace("http://", "").replace("https://", "");
		}
    	
        
    }  
    
    public static void main(String[] args) {
		System.err.println(getDomain("www.baidu.com")); 
	}
}
